using System;
using System.Text;
using System.IO;

public static class Program {
	public static void Main(String[] args) {
		if (args.Length != 4) {
			Console.WriteLine(
				"CodePageConverter <SrcFile> <SrcCodePage> <DstFile> <DstCodePage>{0}{0}" +
				"Examples:{0}" +
				"   CodePageConverter InFile.txt 65001 OutFile.txt 1200{0}" +
				"      => Converts from UTF-8 (codepage 65001) to UTF-16 (Little Endian){0}{0}" +
				"   CodePageConverter InFile.txt 932 OutFile.txt UTF-8{0}" +
				"      => Converts from shift-jis (codepage 932) to UTF-8",
				Environment.NewLine);
			return;
		}

		// Open the source stream using the specified encoding
		StreamReader srcText = new StreamReader(args[0], GetEncoding(args[1]));

		// Create the destination stream using the specified encoding
		StreamWriter dstText = new StreamWriter(args[2], false, GetEncoding(args[3]));

		// Read from the source stream and write to the destination stream
		dstText.Write(srcText.ReadToEnd());

		// Close both streams
		srcText.Close();
		dstText.Close();
	}

	static Encoding GetEncoding(String s) {
		try {
			// Assume the user passed an integer identifying a code page
			return Encoding.GetEncoding(Int32.Parse(s));
		}
		catch (FormatException) {
			// The user didn't pass an integer code page value
		}

		// Assume the user passed a string identifying a code page
		return Encoding.GetEncoding(s);
	}
}
